package com.itxiuyixiu.tools.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itxiuyixiu.tools.util.returns.ReturnVo;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 黄磊
 * @date 2020/2/9
 */
public class ApiLoginFailureHandler implements AuthenticationFailureHandler {
    private static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setStatus(200);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("content-type", "application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new ReturnVo(HttpStatus.UNAUTHORIZED, "登录失败：账号或者密码错误")));
    }
}
